package com.datounet.flutterapp.Locat;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.datounet.flutterapp.Bean.BeanUser;
import com.datounet.flutterapp.Bean.BeanWsBase;
import com.datounet.flutterapp.MyApplication;
import com.datounet.flutterapp.R;
import com.datounet.flutterapp.WebSocket.SocketMgr;
import com.datounet.flutterapp.methodChannel.MethodChannelPlugin;
import com.datounet.flutterapp.methodChannel.MethodTypes;
import com.google.gson.Gson;

import java.util.Map;


public class LocationMgr {
    private static final String TAG = "LocationMgr";
    private static AMapLocationClient mLocationClient;

    private static final String NOTIFICATION_CHANNEL_NAME = "BackgroundLocation";
    private static NotificationManager notificationManager = null;
    private static boolean isCreateChannel = false;
    private static Gson gson = new Gson();

    public static void init(Context context) {
        //声明AMapLocationClient类对象
        mLocationClient = new AMapLocationClient(context);
        //初始化AMapLocationClientOption对象
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(5000);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为true，允许模拟位置
        mLocationOption.setMockEnable(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(30000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

        //设置定位回调监听
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        //可在其中解析aMapLocation获取相应内容。
                        Log.e(TAG, "onLocationChanged: " + aMapLocation.toStr());
                        sendLatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude());
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e(TAG, "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        });
    }

    private static void sendLatLng(double lat,double lng) {
        if (BeanUser.role_id == 4) {
            Map map=BeanUser.getMap();
            map.put("latitude",lat);
            map.put("longitude",lng);
            SocketMgr.sendMsg(gson.toJson(new BeanWsBase<>(8,map)));
        }
    }

    public static void startLocating() {
        if (mLocationClient == null) {
            Log.e(TAG, "startLocating: LocationClient is null");
            return;
        }
        stopLocating();
        //启动定位
        mLocationClient.startLocation();
        mLocationClient.enableBackgroundLocation(2001, buildNotification());
    }

    public static void stopLocating() {
        if (mLocationClient == null) {
            return;
        }
        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        mLocationClient.disableBackgroundLocation(true);
    }

    public static void dispose() {
        if (mLocationClient == null) {
            return;
        }
        mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }

    private static Notification buildNotification() {
        Notification.Builder builder = null;
        Notification notification = null;
        if (android.os.Build.VERSION.SDK_INT >= 26) {
            //Android O上对Notification进行了修改，如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
            if (null == notificationManager) {
                notificationManager = (NotificationManager) MyApplication.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
            }
            String channelId = MyApplication.getInstance().getPackageName();
            if (!isCreateChannel) {
                NotificationChannel notificationChannel = new NotificationChannel(channelId,
                        NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
                notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
                notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                notificationManager.createNotificationChannel(notificationChannel);
                isCreateChannel = true;
            }
            builder = new Notification.Builder(MyApplication.getInstance(), channelId);
        } else {
            builder = new Notification.Builder(MyApplication.getInstance());
        }
        builder.setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("邻客专送")
                .setContentText("正在后台运行")
                .setWhen(System.currentTimeMillis());

        if (android.os.Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
        } else {
            return builder.getNotification();
        }
        return notification;
    }

}
